package com.shenzhenai.composesideeffects.samples

import android.util.Log
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.tooling.preview.Preview
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.filter

/**
 * @author huangzehui
 * @date 20/9/2025 下午11:26 周六
 * @description
 *
 * 86-snapshotFlow
 * https://www.bilibili.com/video/BV1ob4y1a7ad?spm_id_from=333.788.videopod.episodes&vd_source=e07cc8cc94eb22bd76722071b03cd199&p=86
 *
 */

@Composable
fun SnapshotFlowSample() {
    // 可复用列表的状态
    val listState = rememberLazyListState()

    LazyColumn(state = listState) {
        items(1000) { index ->
            Text(text = "Item ${index}")
        }
    }


    LaunchedEffect(listState) {
        snapshotFlow {
            // 首个可见item的角标
            listState.firstVisibleItemIndex
        }
            .filter { it > 20 }
            // 去重
            .distinctUntilChanged()
            .collect {
                Log.d("young_tesjkjdkf", "firstVisibleItemIndex:${it}")
            }


    }
}


@Preview
@Composable
fun SnapshotFlowSamplePreview() {
    SnapshotFlowSample()
}